package com.laoxu.web.controller;

import com.laoxu.web.dao.DepartmentDao;
import com.laoxu.web.dao.EmployeeDao;
import com.laoxu.web.entities.Department;
import com.laoxu.web.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

/**
 * 员工控制器
 *
 * @author xusucheng
 * @create 2019-01-13
 **/
@Controller
public class EmployeeController {
    @Autowired
    EmployeeDao employeeDao;

    @Autowired
    DepartmentDao departmentDao;

    /**
     * 查询员工列表
     * @param model
     * @return
     */
    @GetMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.getAll();
        model.addAttribute("emps", employees);

        return "emp/list";
    }

    /**
     * 添加员工页面
     * @return
     */
    @GetMapping("/emp")
    public String toAddPage(Model model){
        //查询所有部门
        Collection<Department> depsartments = departmentDao.getDepartments();
        model.addAttribute("depts",depsartments);
        return "emp/add";
    }

    /**
     * 添加员工
     * @param employee
     * @return
     */
    @PostMapping("/emp")
    public String addEmp(Employee employee){
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    /**
     * 修改员工页面
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/emp/{id}")
    public String toEditPage(@PathVariable("id") Integer id, Model model){
        Employee employee = employeeDao.get(id);
        //查询所有部门
        Collection<Department> depsartments = departmentDao.getDepartments();
        model.addAttribute("depts",depsartments);
        model.addAttribute("emp", employee);


        return "emp/add";
    }

    @PutMapping("/emp")
    public String updateEmployee(Employee employee){
        employeeDao.save(employee);


        return "redirect:/emps";
    }

    @DeleteMapping("/emp/{id}")
    public String deleteEmployee(@PathVariable("id") Integer id){
        employeeDao.delete(id);

        return "redirect:/emps";
    }


}
